//
//  SetUpGroupViewController.m
//  Findif
//
//  Created by Mac on 2019/2/21.
//  Copyright © 2019年 Cicel Chen. All rights reserved.
//

#import "SetUpGroupViewController.h"
#import "GroupInfoViewController.h"
#import "ServerStatementViewController.h"

@interface SetUpGroupViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate,UITextFieldDelegate>{
    
    UIImagePickerController *_imagePickerController;
}

@property (nonatomic, weak)UIButton * addButton;
@property (nonatomic, weak)UITextField * nameTextField;
@property (nonatomic, weak)UIView * lineView;
@property (nonatomic, strong)UIButton * eatButton;
@property (nonatomic, strong)UIButton * playButton;
@property (nonatomic, strong)UIButton * sportsButton;
@property (nonatomic, strong)UIButton * travelButton;
@property (nonatomic, weak)UIButton * applyButton;
@property (nonatomic, weak)UIButton * checkButton;
@property (nonatomic, weak)UIButton * serviceButton;
@property (nonatomic, strong)UIAlertController * alertVC;
@property (nonatomic, copy)NSString * img;
@property (nonatomic, strong)NSMutableArray * buttonArray;
@property (nonatomic, weak)UILabel * seeLabel;
@property (nonatomic, weak)UIButton * privilegeButton;
@property (nonatomic, weak)UILabel * signLabel;

@end

@implementation SetUpGroupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"创建";
    self.view.backgroundColor = ZRWhiteColor;
    self.buttonArray = [NSMutableArray array];
    
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    
    [self setupUI];
    [self setupAlertVC];
}


- (void)setupUI{
    
    UIButton * addButton = [UIButton new];
    
    [addButton setImage:[UIImage imageNamed:@"添加头像"] forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(clickAddButton) forControlEvents:UIControlEventTouchUpInside];
    addButton.layer.cornerRadius = 62.5  * SCREENH6;
    addButton.layer.masksToBounds = YES;
    
    self.addButton = addButton;
    
    [self.view addSubview:self.addButton];
    
    
    UITextField * nameTextField = [[UITextField alloc] init];
    
    nameTextField.borderStyle = UITextBorderStyleNone;
    nameTextField.backgroundColor = ZRWhiteColor;
//    textFiled.layer.borderColor = [[UIColor clearColor] CGColor];
    //设置光标颜色
    nameTextField.tintColor = ZRBlackColor;
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0x909090);
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    nameTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"填写社团称号（2~15字）" attributes:attrs];
    nameTextField.textColor = ZRBlackColor;
    //    textFiled.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22 * SCREENH6, 0)];
    //    //设置显示模式为永远显示(默认不显示)
    //    textFiled.leftViewMode = UITextFieldViewModeAlways;
    nameTextField.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
//    nameTextField.delegate = self;
    nameTextField.textAlignment = NSTextAlignmentCenter;
    nameTextField.delegate = self;
    
    self.nameTextField = nameTextField;
    
    [self.view addSubview:self.nameTextField];
    
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xababab);
    
    self.lineView = lineView;
    
    [self.view addSubview:self.lineView];
    
    
    self.eatButton = [self setupButtonWithTitle:@" 吃喝 "];
    self.eatButton.tag = 1137;
    [self.view addSubview:self.eatButton];
    self.playButton = [self setupButtonWithTitle:@" 玩乐 "];
    self.playButton.tag = 1138;
    [self.view addSubview:self.playButton];
    self.sportsButton = [self setupButtonWithTitle:@" 运动 "];
    self.sportsButton.tag = 1139;
    [self.view addSubview:self.sportsButton];
    self.travelButton = [self setupButtonWithTitle:@" 旅行 "];
    self.travelButton.tag = 1140;
    [self.view addSubview:self.travelButton];
    
    [self.buttonArray addObject:self.eatButton];
    [self.buttonArray addObject:self.playButton];
    [self.buttonArray addObject:self.sportsButton];
    [self.buttonArray addObject:self.travelButton];
    
    UIButton * applyButton = [UIButton new];
    
    [applyButton setBackgroundColor:ZRBlackColor];
    [applyButton setTitle:@"立即提交" forState:UIControlStateNormal];
    [applyButton setTitleColor:ZRWhiteColor forState:UIControlStateNormal];
    applyButton.titleLabel.font = [UIFont systemFontOfSize:16 * SCREENH6];
    applyButton.layer.cornerRadius = 5 * SCREENH6;
    applyButton.layer.masksToBounds = YES;
    [applyButton addTarget:self action:@selector(clickApplyButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.applyButton = applyButton;
    
    [self.view addSubview:self.applyButton];
    
    
    UIButton * checkButton = [UIButton new];
    
    checkButton.adjustsImageWhenHighlighted = NO;
    [checkButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    [checkButton setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
    [checkButton setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateSelected];
    [checkButton setTitle:@" 我已阅读并同意" forState:UIControlStateNormal];
    checkButton.titleLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    [checkButton addTarget:self action:@selector(clickTagButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.checkButton = checkButton;
    
    [self.view addSubview:self.checkButton];
    
    
    UIButton * serviceButton = [UIButton new];
    
    [serviceButton setTitleColor:ColorWithRGB(0xFF5C5C) forState:UIControlStateNormal];
    [serviceButton setTitle:@"服务声明" forState:UIControlStateNormal];
    serviceButton.titleLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    [serviceButton addTarget:self action:@selector(clickTagButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.serviceButton = serviceButton;
    
    [self.view addSubview:self.serviceButton];
    
    
    UILabel * seeLabel = [UILabel new];
    
    seeLabel.text = @"【看看你有哪些";
    seeLabel.textColor = [UIColor lightGrayColor];
    seeLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    
    self.seeLabel = seeLabel;
    
    [self.view addSubview:self.seeLabel];
    
    UIButton * privilegeButton = [UIButton new];
    
    [privilegeButton setTitle:@"社长特权" forState:UIControlStateNormal];
    [privilegeButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [privilegeButton addTarget:self action:@selector(clickPrivilegeButton) forControlEvents:UIControlEventTouchUpInside];
    privilegeButton.titleLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    
    self.privilegeButton = privilegeButton;
    
    [self.view addSubview:self.privilegeButton];
    
    UILabel * signLabel = [UILabel new];
    
    signLabel.text = @"】";
    signLabel.textColor = [UIColor lightGrayColor];
    signLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    
    self.signLabel = signLabel;
    
    [self.view addSubview:self.signLabel];
}


- (void)viewDidLayoutSubviews{
    
    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(topHeight + 80 * SCREENH6);
        make.width.height.mas_equalTo(125 * SCREENH6);
    }];
    
    [self.nameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.addButton.mas_bottom).offset(45 * SCREENH6);
        make.height.mas_equalTo(35 * SCREENH6);
        make.width.mas_equalTo(305 * SCREENH6);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.nameTextField.mas_bottom).offset(5 * SCREENH6);
        make.height.mas_equalTo(1 * SCREENH6);
        make.width.mas_equalTo(305 * SCREENH6);
    }];
    
    [self.seeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(115 * SCREENH6);
        make.top.mas_equalTo(self.lineView.mas_bottom).offset(15 * SCREENH6);
    }];
    
    [self.privilegeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.seeLabel);
        make.leading.mas_equalTo(self.seeLabel.mas_trailing);
    }];
    
    [self.signLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.privilegeButton);
        make.leading.mas_equalTo(self.privilegeButton.mas_trailing);
    }];
    
    [self.eatButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(70 * SCREENH6);
        make.top.mas_equalTo(self.lineView.mas_bottom).offset(50 * SCREENH6);
        make.height.mas_equalTo(20 * SCREENH6);
        make.width.mas_equalTo(50 * SCREENH6);
    }];
    
    [self.playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.width.height.mas_equalTo(self.eatButton);
        make.leading.mas_equalTo(self.eatButton.mas_trailing).offset(10 * SCREENH6);
    }];
    
    [self.sportsButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.width.height.mas_equalTo(self.playButton);
        make.leading.mas_equalTo(self.playButton.mas_trailing).offset(10 * SCREENH6);
    }];
    
    [self.travelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.width.height.mas_equalTo(self.sportsButton);
        make.leading.mas_equalTo(self.sportsButton.mas_trailing).offset(10 * SCREENH6);
    }];
    
    [self.applyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.eatButton.mas_bottom).offset(90 * SCREENH6);
        make.width.mas_equalTo(250 * SCREENH6);
        make.height.mas_equalTo(30 * SCREENH6);
    }];
    
    [self.checkButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(102 * SCREENH6);
        make.top.mas_equalTo(self.applyButton.mas_bottom).offset(18 * SCREENH6);
    }];
    
    [self.serviceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.checkButton);
        make.leading.mas_equalTo(self.checkButton.mas_trailing).offset(5 * SCREENH6);
    }];
}

- (UIButton *)setupButtonWithTitle:(NSString *)title{
    
    UIButton * button = [UIButton new];
    
    button.adjustsImageWhenHighlighted = NO;
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:ZRWhiteColor forState:UIControlStateNormal];
//    UIImage *img = [self imageWithColor:[UIColor colorWithRed:207 green:207 blue:207 alpha:1]];
    [button setBackgroundImage:[self imageWithColor:ColorWithRGB(0xCFCFCF)] forState:UIControlStateNormal];
//    [button setBackgroundColor:[UIColor redColor]];
    [button addTarget:self action:@selector(clickTagButton:) forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    button.layer.cornerRadius = 10 * SCREENH6;
    button.layer.masksToBounds = YES;
    if ([title isEqualToString:@" 吃喝 "]) {
        
        [button setBackgroundImage:[self imageWithColor:ColorWithRGB(0xEB7664)] forState:UIControlStateSelected];
    }else if ([title isEqualToString:@" 玩乐 "]){
        
        [button setBackgroundImage:[self imageWithColor:ColorWithRGB(0xAD77E9)] forState:UIControlStateSelected];
    }else if ([title isEqualToString:@" 运动 "]){
        
        [button setBackgroundImage:[self imageWithColor:ColorWithRGB(0x72D9AA)] forState:UIControlStateSelected];
    }else if ([title isEqualToString:@" 旅行 "]){
        
        [button setBackgroundImage:[self imageWithColor:ColorWithRGB(0x6AA3F1)] forState:UIControlStateSelected];
    }

    return button;
}


- (void)clickAddButton{
    
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        
        self.alertVC.popoverPresentationController.sourceView = self.view;
        self.alertVC.popoverPresentationController.sourceRect = CGRectMake(10 * SCREENH6,kScreenH - 150 * SCREENH6,355 * SCREENH6,150 * SCREENH6);
        //            self.alertVC.modalPresentationStyle = UIModalPresentationFormSheet;
    }
    [self presentViewController:self.alertVC animated:YES completion:nil];
}

- (void)clickApplyButton{
    
    if (!self.img) {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"请先添加社团头像"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    }else if(self.nameTextField.text.length == 0){
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"请先添写社团名称"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else if(!self.eatButton.selected && !self.playButton.selected && !self.sportsButton.selected && !self.travelButton.selected){
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"请先至少选择一个社团分类"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else if(!self.checkButton.selected){
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"请先阅读及同意服务声明"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        ShowHUD;
        NSMutableArray * arr = [NSMutableArray array];
        
        for (UIButton * button in self.buttonArray) {
            
            if (button.selected) {
                NSString * tag = [NSString stringWithFormat:@"%ld",(long)button.tag];
                [arr addObject:tag];
            }
        }
        
        NSString * group_category = [arr.copy componentsJoinedByString:@","];
        
        NSDictionary * dict = @{@"group_name":self.nameTextField.text,@"group_img":self.img,@"group_category":group_category};
        
        [[ZRNetworkTool sharedTool] createGroupWithDict:dict WithBlock:^(BOOL success, id responseData) {
            
            HiddenHUD;
            if (success) {
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                          NSString * ID = [NSString stringWithFormat:@"%@",responseData[@"data"]];
                                                                          
                                                                          HiddenBar;
                                                                          GroupInfoViewController * infoVC = [GroupInfoViewController new];
                                                                          
                                                                          infoVC.group_id = ID;
                                                                          
                                                                          [self.navigationController pushViewController:infoVC animated:YES];
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                         
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
        
    }
    
}

- (void)clickTagButton:(UIButton *)button{
    
//    button.highlighted = NO;
    button.selected = !button.selected;
    
    if (button == self.serviceButton) {
        
        HiddenBar;
        ServerStatementViewController * serverVC = [ServerStatementViewController new];
        
        serverVC.url = @"https://findif.cn/serverStatement.html";
        serverVC.titleStr = @"服务声明";
        
        [self.navigationController pushViewController:serverVC animated:YES];
    }
}


- (void)setupAlertVC{
    
    self.alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"选择照片方式" preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * camerAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * albumsAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        self->_imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        [self presentViewController:self->_imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [self.alertVC addAction:camerAction];
    [self.alertVC addAction:albumsAction];
    [self.alertVC addAction:cancelAction];
    
}

#pragma mark -实现图片选择器代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{}];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    NSData *frontImageData = UIImageJPEGRepresentation(image,0.5);
    NSString *base64Data = [frontImageData base64EncodedStringWithOptions:0];
    NSString * reslut = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",base64Data];
    
    
    [[ZRNetworkTool sharedTool] uploadOneImgResultWithImg:reslut WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            [self.addButton setImage:image forState:UIControlStateNormal];
            self.img = [NSString stringWithFormat:@"%@",responseData[@"data"]];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
    
}

//当用户取消选择的时候，调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{}];
}

- (UIImage *)imageWithColor:(UIColor *)color
{
    
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    CGContextFillRect(context, rect);
    
    
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    
    
    return image;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        //so easy
        else if (self.nameTextField.text.length >= 15) {
            self.nameTextField.text = [textField.text substringToIndex:15];
            return NO;
        }

    return YES;
}


- (void)clickPrivilegeButton{
    
    HiddenBar;
    ServerStatementViewController * serverVC = [ServerStatementViewController new];
    
    serverVC.url = @"https://findif.cn/president.html";
    serverVC.titleStr = @"社长特权";
    
    [self.navigationController pushViewController:serverVC animated:YES];
}

@end
